package com.leo.chapter06;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 用Exector来创建一个简单的线程池，缓解了线程开销可能太大问题
 * @author xuexiaolei
 * @version 2017年10月15日
 */
public class TaskExecutionWebServer {
    private static final int NTHREADS = 100;
    private static final Executor exec = Executors.newFixedThreadPool(NTHREADS);

    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (true){
            Socket connection = socket.accept();
            Runnable task = new Runnable() {
                @Override public void run() {
                    handleRequest(connection);
                }
            };
            exec.execute(task);
        }
    }


    /**
     * 正真的处理要求线程安全
     * @param connection
     */
    public static void handleRequest(Socket connection){
        try {
            System.out.println("正在处理");
            Thread.sleep(1000);
            System.out.println("处理完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
